package com.sofaguest.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.sofaguest.dao.LogDao;
import com.sofaguest.dao.MsgDao;
import com.sofaguest.dao.SofaDao;
import com.sofaguest.entry.LogInfo;
import com.sofaguest.entry.MsgInfo;
import com.sofaguest.entry.SofaInfo;
import com.sofaguest.entry.SofaResult;
import com.sofaguest.utils.SofaUtils;

/**
 * 对沙发进行操作的业务层
 * @author Administrator
 */
@Service
@Transactional
public class SofaServiceImpl implements SofaService {

    Logger log = Logger.getLogger("SofaServiceImpl");

    @Resource
    private SofaDao sofaDao;
    @Resource
    private LogDao logDao;
    @Resource
    private MsgDao msgDao;

    // 查询沙发的简单信息信息
    @Override
    public SofaResult qrySimpleSofa(String address, String sex, int minAge, int maxAge, int pernum) {
        log.info("====查询沙发简单信息:");
        if (SofaUtils.isEmpty(minAge)) {
            minAge = 0;
        }
        if (SofaUtils.isEmpty(maxAge)) {
            maxAge = 99;
        }
        if ("null".equals(address)) { // 全部查询
            address = null;
            sex = null;
        }
        Map dataMap = SofaUtils.asMap("address", address, "sex", sex, "minAge", minAge, "maxAge", maxAge, "perNum",
                pernum);
        List<SofaInfo> sofaInfo = sofaDao.qrySimpleSofa(dataMap);
        if (SofaUtils.isEmpty(sofaInfo)) {
            return new SofaResult(SofaResult.ERROR_CODE, "未查询到合适的沙发信息", "");
        }
        for (SofaInfo sofa : sofaInfo) {
            byte[] sofapic = (byte[]) sofa.getSofa_emg();
            String picPath = SofaUtils.PIC_PATH + "pic" + sofa.getSofa_id() + ".png";
            File picFile = new File(picPath);
            if (!picFile.exists()) {

                try {
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(picPath)));
                    stream.write(sofapic);
                    stream.close();
                }
                catch (Exception e) {
                    e.printStackTrace();
                    return new SofaResult(SofaResult.ERROR_CODE, "图片加载失败!", "");
                }
            }
            sofa.setSofa_emg(picPath.substring(picPath.indexOf("/sofapic")));
        }
        return new SofaResult(SofaResult.SUCCESS_CODE, "查询成功", sofaInfo);
    }

    /**
     * 获取沙发的详细信息
     */
    @Override
    public SofaResult qrySofa(String sofaId) {
        if (SofaUtils.isEmpty(sofaId)) {
            return new SofaResult(SofaResult.ERROR_CODE, "未获取到要查看的沙发ID!", "");
        }
        // 1.查询沙发信息
        List<SofaInfo> sofaInfo = sofaDao.qrySofa(sofaId);
        if (SofaUtils.isEmpty(sofaInfo)) {
            return new SofaResult(SofaResult.ERROR_CODE, "查询沙发的详细信息失败!", "");
        }
        SofaInfo sofa = sofaInfo.get(0);
        if ("0".equals(sofa.getCan_use_tag())) {
            return new SofaResult(SofaResult.ERROR_CODE, "该沙发已被预定,请重新选择", "");
        }
        // 2.加载沙发图片信息
        byte[] sofapic = (byte[]) sofa.getSofa_emg();
        String picPath = SofaUtils.PIC_PATH + "pic" + sofa.getSofa_id() + ".png";
        File picFile = new File(picPath);
        if (!picFile.exists()) {

            try {
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(picPath)));
                stream.write(sofapic);
                stream.close();
            }
            catch (Exception e) {
                e.printStackTrace();
                return new SofaResult(SofaResult.ERROR_CODE, "图片加载失败!", "");
            }
        }
        sofa.setSofa_emg(picPath.substring(picPath.indexOf("/sofapic")));
        // TODO: 获取沙发的评论信息,已添加
        List<MsgInfo> msgInfo = msgDao.getMassageInfo(sofa.getSofa_id());
        for (MsgInfo msg : msgInfo) {
            String autor = logDao.login(msg.getUser_id()).getReal_name();
            msg.setUser_id(autor);
        }
        // 获取沙发主人的姓名
        LogInfo hostInfo = logDao.login(sofa.getHost_id());
        sofa.setHost_id(hostInfo.getReal_name());
        Map dataMap = SofaUtils.asMap("sofaInfo", sofa, "msgInfo", msgInfo);
        return new SofaResult(SofaResult.SUCCESS_CODE, "查询成功", dataMap);
    }

    // 添加沙发图片
    @Override
    public SofaResult addSofaEmg(MultipartFile sofapic, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        log.info("=======添加沙发图片");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        byte[] logoBytes = null;
        if (!sofapic.isEmpty()) {
            try {
                logoBytes = sofapic.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File("sofapic")));
                stream.write(logoBytes);
                stream.close();
            }
            catch (Exception e) {
                return new SofaResult(SofaResult.ERROR_CODE, "上传图片出错!请重新上传", "");
            }
        }
        else {
            return new SofaResult(SofaResult.ERROR_CODE, "上传的图片有误!请重新选择", "");
        }
        if (SofaUtils.isEmpty(logoBytes) || logoBytes.length > 50 * 1024) {
            return new SofaResult(SofaResult.ERROR_CODE, "上传图片过大!请重新选择", "");
        }
        String sofaId = SofaUtils.createSofaID();
        SofaInfo sofa = new SofaInfo(sofaId, "", "", "", "", "", "", 0, 99, "", "", 2, 0, 5.0, "", "", "", logoBytes,
                "", "", "", "", "");
        sofa.setValid_flag("0");// 设置为失效
        sofa.setUnuse_time(SofaUtils.getSysDate());// 设置为失效
        sofaDao.addSofaEmg(sofa);
        return new SofaResult(SofaResult.SUCCESS_CODE, "图片上传成功", sofaId);
    }

    // 添加沙发
    @Override
    public SofaResult addSofa(String sofaId, String hostId, String sofaname, String sofaAddress, String sofaType,
            String maxper, String sexlim, String agelim, String linkTel, String mail, String mixday, String baseres,
            String explain) {
        log.info("======添加沙发");
        if (SofaUtils.isEmpty(agelim) || !agelim.contains("-") || (agelim.split("-")).length > 2) {
            return new SofaResult(SofaResult.ERROR_CODE, "年龄限制参数有误,请检查! 年龄限制:" + agelim, "");
        }
        String[] age = agelim.split("-");
        int maxtime = 0;
        int minAge = 0;
        int maxAge = 0;
        try {
            maxtime = Integer.valueOf(mixday);
            minAge = Integer.valueOf(age[0]);
            maxAge = Integer.valueOf(age[1]);
            Integer.valueOf(maxper);
        }
        catch (Exception e) {
            return new SofaResult(SofaResult.ERROR_CODE, "传入的数字有误!最长入住时间:" + mixday + "年龄限制:" + agelim + "最大接待人数:"
                    + maxper, "");
        }
        if (minAge > maxAge) {
            return new SofaResult(SofaResult.ERROR_CODE, "年龄限制参数有误,请检查!", agelim);
        }
        // String ownGoods = Arrays.toString(baseres);
        Object sofaEmg = ""; // 更新的时候入库不更新该字段
        String joinTime = SofaUtils.getSysDate();
        if (!SofaUtils.isEmpty(baseres) && baseres.endsWith(",")) {
            baseres = baseres.substring(0, baseres.length() - 1);
        }
        SofaInfo sofa = new SofaInfo(sofaId, sofaname, hostId, sofaAddress, sofaType, maxper, sexlim, minAge, maxAge,
                mail, linkTel, maxtime, 0, 0, "1", baseres, explain, sofaEmg, joinTime, "1", "", "", "");
        sofa.setValid_flag("1");// 设置为生效
        sofa.setUnuse_time("");// 失效时间更新为空
        sofaDao.addSofaBySofaId(sofa); // 修改沙发信息也走这里
        return new SofaResult(SofaResult.SUCCESS_CODE, "沙发添加成功!", "");
    }

    @Override
    public SofaResult qrySofaList() {
        return new SofaResult(SofaResult.SUCCESS_CODE, "查询成功", sofaDao.getSofaList());
    }

    @Override
    public SofaResult qrySofaByHostId(String hostId) {
        List<SofaInfo> sofas = sofaDao.qrySofaByHostId(hostId);
        String detial = "查询成功";
        String status = SofaResult.SUCCESS_CODE;
        if (SofaUtils.isEmpty(sofas)) {
            detial = "您暂时还未发布沙发信息";
            status = SofaResult.ERROR_CODE;
        }
        return new SofaResult(status, detial, sofas);
    }

    @Override
    public SofaResult getSofaList(int byTimeTag) {
        List<Map> sofas = sofaDao.getSofaListForManager(byTimeTag);
        return new SofaResult(SofaResult.SUCCESS_CODE, "查询成功", sofas);
    }
}
